package com.xone.xapp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class BannerUserAdapter extends BasicListAdapter<BannerListUserHolder> {
	
	protected ImageLoader imgLoader;
	protected Context context;
	protected LayoutInflater mInflater;
	public BannerUserAdapter(Context context, List<JSONObject> list) {
		this.context = context;
		this.list = initWithJsonList(list);
		imgLoader = new ImageLoader(context);
		this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public List<BannerListUserHolder> initWithJsonList(List<JSONObject> list) {
		if (JSONUtils.isNullOrEmptyList(list)) {
			return Collections.emptyList();
		}
		List<BannerListUserHolder> result = new ArrayList<BannerListUserHolder>();
		for (int i = 0; i < list.size(); i++) {
			result.add(new BannerListUserHolder(list.get(i)));
		}
		return result;
	}
	
	/**
	 * 取得置顶的最后一个元素的位置
	 * @return
	 */
	public int getTopLastIndex() {
		return -1;
	}

	@Override
	public View getView(int position, View view, ViewGroup parent) {
		ViewHolder viewHolder;
		if (view == null) {
			viewHolder = new ViewHolder();
			view = this.mInflater.inflate(R.layout.banner_listview_user, null);
			viewHolder.setIconView((ImageView)view.findViewById(R.id.icon));
			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder)view.getTag();
		}
		BannerListUserHolder holder = list.get(position);
		final String id = holder.getId();
		String imageId = holder.getAdRefId();
		if (StringUtils.isNotBlank(imageId)) {
			imgLoader.displayImage(Constants.APP_URL + "/assistant/image.html?id=" + imageId, viewHolder.getIconView());
		}
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(context, BannerItemUserActivity.class);
				i.putExtra("id", id);
				context.startActivity(i);
			}
		});
		return view;
	}
	
	protected class ViewHolder {
		protected ImageView iconView;
		public ImageView getIconView() {
			return iconView;
		}
		public void setIconView(ImageView iconView) {
			this.iconView = iconView;
		}
	}

}
